import React, {PureComponent, Fragment} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio, Table, Popconfirm,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './List.less';

const FormItem = Form.Item;
const {Step} = Steps;
const {TextArea} = Input;
const {Option} = Select;
const RadioGroup = Radio.Group;

/* eslint react/no-multi-comp:0 */
@connect(({category, loading}) => ({
  category,
  loading: loading.effects['category/fetch'],
}))
@Form.create()
class ActiveCategory extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    formValues: {},
    updateValue: {},
  };
  columns = [
    {
      title: '序号',
      dataIndex: 'categoryId',
    },
    {
      title: '类别名称',
      dataIndex: 'name',
    },
    {
      title: '状态',
      // dataIndex: 'status',
      dataIndex:"state"
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: (a, b) => Date.parse(a.createTime)>Date.parse(b.createTime),
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      sorter: (a, b) => Date.parse(a.updateTime)>Date.parse(b.updateTime),
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      render: (text, item) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, item)}>修改</a>
          <Divider type="vertical"/>
          <Popconfirm onConfirm={() => this.cateogryDelete(item.categoryId)} title="确定删除该类别吗？"
                      icon={<Icon type="question-circle-o" style={{color: 'red'}}/>}>
            <a><Icon type="delete" style={{marginRight: 8}}/>删除</a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'category/fetch',
      payload: {type:"activity"}
    });
  }
  cateogryDelete=(categoryId)=>{
    this.props.dispatch({
      type: 'category/delete',
      payload: {type:"activity",id:categoryId}
    });
  }
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    console.log("some data change")
  };

  handleFormReset = () => {
    const {form, dispatch} = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'category/fetch',
      payload: {type:"activity"},
    });
  };

  toggleForm = () => {
    const {expandForm} = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const {dispatch, form} = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'category/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = (flag,item) => {
    this.setState({
      modalVisible: !!flag,
      updateValue:item||{}
    });
  };
  handleAdd = fields => {
    const {dispatch} = this.props;
    dispatch({
      type: 'category/save',
      payload:fields,
    });
    this.handleModalVisible();
  };
  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="菜单名称">
              {getFieldDecorator('name')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="菜单状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{marginLeft: 8}} onClick={this.toggleForm}>
                展开 <Icon type="down"/>
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="菜单名称">
              {getFieldDecorator('name')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="菜单状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="创建日期">
              {getFieldDecorator('createDate')(
                <DatePicker style={{width: '100%'}} placeholder="请输入创建日期"/>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="更新日期">
              {getFieldDecorator('updateDate')(
                <DatePicker style={{width: '100%'}} placeholder="请输入更新日期"/>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('status3')(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('status4')(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{overflow: 'hidden'}}>
          <div style={{float: 'right', marginBottom: 24}}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{marginLeft: 8}} onClick={this.toggleForm}>
              收起 <Icon type="up"/>
            </a>
          </div>
        </div>
      </Form>
    );
  }

  renderForm() {
    const {expandForm} = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const {
      category: {list},
      loading,
    } = this.props;
    const {selectedRows, modalVisible} = this.state;
    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    return (
      <PageHeaderWrapper title="类别列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            {/*<div className={styles.tableListForm}>{this.renderForm()}</div>*/}
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新建
              </Button>
            </div>
            <Table
              loading={loading}
              dataSource={list}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} updateValue={this.state.updateValue} modalVisible={modalVisible}/>
      </PageHeaderWrapper>
    );
  }
}

const CreateForm = Form.create()(props => {
  const {modalVisible, form, handleAdd, handleModalVisible,updateValue} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      console.log("updatevalue",JSON.stringify(updateValue))
      if(updateValue&&updateValue.categoryId){
        handleAdd({...fieldsValue,type:"activity",categoryId:updateValue.categoryId});
      }else{
        handleAdd({...fieldsValue,type:"activity",});
      }
    });
  };
  return (
    <Modal
      destroyOnClose
      title={updateValue?"编辑类别":"新建类别"}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="名称">
        {form.getFieldDecorator('name', {
          initialValue:updateValue.name,
          rules: [{required: true, message: '请输入至少二个字符的类别名称！', min: 2}],
        })(<Input placeholder="请输入"/>)}
      </FormItem>
    </Modal>
  );
});
export default ActiveCategory;
